package com.zmn.oms.task.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Lists;
import com.zmn.base.remind.common.consts.MqConst;
import com.zmn.base.remind.common.enums.AppTypeEnum;
import com.zmn.base.remind.common.enums.ScenesTypeEnum;
import com.zmn.base.remind.common.enums.record.RecordCallStatusEnum;
import com.zmn.base.remind.common.model.record.RecordDRO;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.business.interfaces.work.distribute.DistributeTimeoutBservice;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.remark.OrderRemarkDetailDTO;
import com.zmn.oms.model.dto.timeout.DistributeTimeoutDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsCancelDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalWorkBService;
import com.zmn.track.common.constant.TrackConfigConsts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：工单催单监听
 *
 * @author heciqi
 * @date 2018/11/30 16:53
 */
@AliyunMQListener(topic = "${spring.mq.topic.remind}")
@Component
@Slf4j
public class OrderRemindListener {

    @Resource
    private OrderWorkService orderWorkService;
    @Resource
    private ZsNormalWorkBService zsNormalWorkBService;
    @Resource
    private DistributeTimeoutBservice distributeTimeoutBservice;

    @NacosValue(value = "${call.order.remind.useNewRemind:false}", autoRefreshed = true)
    private Boolean useNewRemind = false;

    @AliyunMQHandler(tags = MqConst.REMIND_IVR_KEY_TAG)
    public void remindRecord(String message) {
        try {
            RecordDRO recordDRO = JSON.parseObject(message, RecordDRO.class);
            if (!Objects.equals(recordDRO.getAppId(), AppTypeEnum.OMS)) {
                return;
            }
            log.info("工单催单通话按键记录消费[{}]", message);
            try {
                // 派单超时外呼结果处理
                this.processDistributeTimeoutCallResult(recordDRO);
            } catch (Exception e) {
                log.error("派单超时外呼结果处理失败 入参：{} ，异常：{}", message, e);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("工单催单通话按键记录消费 处理失败：{}", e);
        }
    }


    /**
     * 派单超时外呼结果处理
     *
     * @param recordDRO
     */
    private void processDistributeTimeoutCallResult(RecordDRO recordDRO) throws OmsBaseException {
        if (!useNewRemind) {
            log.info("未开启新remind外呼");
            return;
        }
        if (!Objects.equals(recordDRO.getScenesType(), ScenesTypeEnum.NO_DISPATCHED_TIME_OUT)) {
            return;
        }
        if (StringUtil.isBlank(recordDRO.getPressKey())) {
            throw new OmsBaseException("用户操作不能为空");
        }
        if (StringUtil.isBlank(recordDRO.getBizId())) {
            throw new OmsBaseException("业务唯一编号不能为空");
        }

        Long workId = Long.valueOf(recordDRO.getBizId());
        String[] userKeyArr = recordDRO.getPressKey().split(",");

        // 查询工单信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(workId, workId);

        // 用户输入等待
        if (Objects.equals(userKeyArr[0], String.valueOf(GlobalConsts.YES))) {
            DistributeTimeoutDTO distributeTimeoutDTO = new DistributeTimeoutDTO();
            distributeTimeoutDTO.setOrderId(workId);
            distributeTimeoutDTO.setWorkId(workId);
            distributeTimeoutDTO.setReasonId(TrackConfigConsts.TRACK_REASON_ID_USER_WAIT);
            distributeTimeoutDTO.setOperator(orderWork.getUserId() == null ? "" : orderWork.getUserId().toString());
            distributeTimeoutDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_USER);
            distributeTimeoutDTO.setOperatorId(orderWork.getUserId());
            distributeTimeoutDTO.setOperatorLogRemark("用户电话按键继续等待");
            log.info("派单超时，用户按键继续等待，发起跟单[{}]", workId);
            distributeTimeoutBservice.timeoutProcess(distributeTimeoutDTO);
            return;
        }

        // 用户选择取消订单
        if (Objects.equals(userKeyArr[0], String.valueOf(GlobalConsts.NO))) {
            try {
                ZsCancelDTO zsCancelDTO = new ZsCancelDTO();
                zsCancelDTO.setOrderId(workId);
                zsCancelDTO.setWorkId(workId);
                List<OrderRemarkDetailDTO> detailDTOList = Lists.newArrayList();
                OrderRemarkDetailDTO dto = new OrderRemarkDetailDTO();
                dto.setMapId(OrderConsts.DISTRIBUTE_TIMEOUT_WAIT_ID);
                dto.setMapName("派单超时用户取消");
                detailDTOList.add(dto);
                zsCancelDTO.setDetailDTOList(detailDTOList);

                // 操作人信息
                zsCancelDTO.setOperator(orderWork.getUserId() == null ? "" : orderWork.getUserId().toString());
                zsCancelDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_USER);
                zsCancelDTO.setOperatorId(orderWork.getUserId());
                zsCancelDTO.setEntranceId(91);
                zsCancelDTO.setOperatorLogRemark("用户电话按键选择取消");

                log.info("派单超时，用户按键取消订单[{}] 入参：{}", workId, JSON.toJSONString(zsCancelDTO));
                zsNormalWorkBService.saveCancel(zsCancelDTO);
            } catch (Exception e) {
                log.error("workId={} 派单超时外呼回调取消订单失败:{}", workId, e);
            }
        }
    }

}
